package com.atjava.nebula.web.view;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.springframework.core.io.ClassPathResource;

import com.atjava.jox.JOXManager;
import com.atjava.jox.io.JOXReader;
import com.atjava.nebula.core.exception.baseExp.SystemException;
import com.atjava.nebula.core.tablexml.view.ViewConfig;

public class XmlViewConfiguration {

	private static Map<String, ViewConfig> viewConfigMap;
	
	static{
		if(viewConfigMap == null){
			viewConfigMap = new HashMap<String, ViewConfig>();
		}
	}
	
	public static ViewConfig readViewConfig(String catalog,String xmlview)throws SystemException{
		String key = catalog + "." + xmlview;
		ViewConfig config = viewConfigMap.get(key);
		
		if(config == null){
			JOXReader reader = new JOXReader();
			JOXManager joxMgr = new JOXManager();
			
			ClassPathResource xmlFile = null;
			try {
				xmlFile = new ClassPathResource(getViewConfigPath(catalog, xmlview));
				if(!xmlFile.exists())
					return null;
				//config = reader.readXml(xmlFile.getFile() ,ViewConfig.class);
				Document doc = reader.readXml(xmlFile.getFile());
				config = joxMgr.getBean(doc.getRootElement(), ViewConfig.class);
				config.setSource(doc.asXML());
				
			} catch (Exception e) {
				throw new SystemException(e,"Read view config xml.["+xmlFile+"]");
			}
			viewConfigMap.put(key, config);
		}
		return config;
	}
	
	
	public static String getViewConfigPath(String catalog,String entity){
		
		return "view/" + catalog + "/"  + entity + ".xml" ;
		
	}
	
}
